<template >
  <view class="order-container" >
    <!-- 订单状态筛选 -->
    <view class="order-filter">
      <text class="filter-item active">全部</text>
      <text class="filter-item">待付款</text>
      <text class="filter-item">配送中</text>
      <text class="filter-item">已完成</text>
      <text class="filter-item">已取消</text>
    </view>

    <!-- 订单列表 -->
    <view class="order-list" v-if="isLoginFlag">
      <view v-for="(order, index) in orders" :key="index" class="order-item">
        <!-- 店铺信息 -->
        <view class="store-info">
          <text class="store-name">{{ order.shopName }}</text>
          <text class="order-status">{{ getStatusText(order.isCanceled) }}</text>
          <text class="order-time">{{ order.orderTime }}</text> <!-- 这里暂时使用当前时间，你可以根据实际数据调整 -->
        </view>

        <!-- 商品列表 -->
        <view class="product-list">
          <view v-for="(productInfo, pIndex) in order.products" :key="pIndex" class="product-item">
            <template v-if="productInfo.product">
              <image class="product-image" :src="productInfo.product.img" />
              <view class="product-info">
                <text class="product-name">{{ productInfo.product.name }}</text>
                <text class="product-price">¥{{ productInfo.product.price }}</text>
                <text class="product-quantity">x{{ productInfo.orderSales }}</text>
              </view>
            </template>
          </view>
        </view>

        <!-- 订单总价和操作 -->
        <view class="order-footer">
          <text class="total-price">
            共{{ getTotalQuantity(order.products) }}件 合计:¥{{ calculateTotalPrice(order.products) }}
          </text>
          <view class="order-actions">
            <text
              v-if="order.isCanceled === '2'"
              class="action-btn confirm-btn"
              @click="confirmReceipt(order)"
            >确认收货</text>
            <text
              v-if="order.isCanceled === '1'"
              class="action-btn cancel-btn"
              @click="cancelOrder(order)"
            >取消订单</text>
          </view>
        </view>
      </view>
    </view>
    <view v-if="!isLoginFlag">
      <view class="register-link" @click="goTologin">还未登录，去登录</view>
    </view>
  </view> 
</template>
<script>
	import  config  from '@/config'
export default {
  data() {
    return {
      isLoginFlag:false,
      orders: [], // 订单数据
      stores: [], // 店铺数据
      statusFilter: 'all', // 当前筛选状态
    };
  },

  onLoad() {
  },

  onShow() {
    try {
      const value = uni.getStorageSync('token');
      const loginUserInfoJSON = uni.getStorageSync('loginUserInfo');
      if (value) {
        this.loginUserInfo = JSON.parse(loginUserInfoJSON);
        this.isLoginFlag = true;
      } else {
        this.isLoginFlag = false;
      }
    } catch (e) {
      console.error(e);
    }
	console.log(this.loginUserInfo)
  this.fetchOrders();
    this.fetchStores();
  },

  methods: {
    // 从后端获取订单数据
    fetchOrders() {
      uni.request({
        url: config.API_HOST+'/order0',
        success: (res) => {
          if (res.statusCode === 200 && Array.isArray(res.data)) {
            // 调整数据结构以匹配你的数据格式
            this.orders = res.data.map((order) => ({
              ...order,
              status: this.getRandomStatus(), // 随机分配状态用于演示
              products: order.products.map((productInfo) => {
                if (!productInfo.product) {
                  productInfo.product = {
                    imgUrl: '/static/default-product.png',
                    name: '未知商品',
                    price: 0
                  };
                }
                return productInfo;
              })
            }));
          } else {
            console.error('获取订单数据失败，状态码:', res.statusCode);
            uni.showToast({
              title: '加载订单失败',
              icon: 'none',
            });
          }
          // console.log(res.data);
        }
      });
    },
    goTologin(){
      uni.navigateTo({
                url: '/pages/login/index' 
            });
    },
    // 从后端获取店铺数据
    fetchStores() {
      uni.request({
        url: config.API_HOST+'/hotList',
        success: (res) => {
          if (res.statusCode === 200 && Array.isArray(res.data)) {
            this.stores = res.data;
          } else {
            console.error('获取店铺数据失败，状态码:', res.statusCode);
          }
          // console.log(this.stores);
        },
        fail: (error) => {
          console.error('获取店铺数据出错:', error);
        },
      });
    },
    getStoreName(storeId) {
      const store = this.stores.find((s) => s._id === storeId || s.id === storeId);
      return store? store.name : '未知店铺';
    },

    // 根据店铺ID获取店铺图标
    getStoreImage(storeId) {
      const store = this.stores.find((s) => s._id === storeId || s.id === storeId);
      return store? store.imgUrl : '/static/default-store.png';
    },

    // 计算商品总数量
    getTotalQuantity(products) {
      if (Array.isArray(products)) {
        return products.reduce((total, productInfo) => total + productInfo.orderSales, 0);
      }
      return 0;
    },

    // 确认收货
    confirmReceipt(order) {
      uni.showModal({
        title: '确认收货',
        content: '确认收到商品了吗？',
        success: (res) => {
          if (res.confirm) {
            // 这里应该调用API更新订单状态
            order.isCanceled = '3'; // 假设3表示已完成
            uni.showToast({
              title: '确认收货成功',
              icon:'success',
            });
          }
        },
      });
    },

    // 取消订单
    cancelOrder(order) {
      uni.showModal({
        title: '取消订单',
        content: '确定要取消此订单吗？',
        success: (res) => {
          if (res.confirm) {
            // 这里应该调用API更新订单状态
            order.isCanceled = '4'; // 假设4表示已取消
            uni.showToast({
              title: '订单已取消',
              icon:'success',
            });
          }
        },
      });
    },

    // 更新订单状态（模拟）
    updateOrderStatus(order, status) {
      this.orders = this.orders.map((o) => {
        if (o === order) {
          return {
           ...o,
            isCanceled: status,
          };
        }
        return o;
      });
    },

    // 获取状态文本
    getStatusText(isCanceled) {
      const statusMap = {
        '1': '待付款',
        '2': '配送中',
        '3': '已完成',
        '4': '已取消',
      };
      return statusMap[isCanceled] || '未知状态';
    },

    // 随机生成订单状态（用于演示）
    getRandomStatus() {
      const statuses = ['1', '2', '3', '4'];
      return statuses[Math.floor(Math.random() * statuses.length)];
    },

    // 格式化订单时间
    formatOrderTime(orderTime) {
      const date = new Date(orderTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

    // 计算订单总价
    calculateTotalPrice(products) {
        if (Array.isArray(products)) {
            const total = products.reduce((total, productInfo) => {
                if (productInfo.product && typeof productInfo.product.price === 'number') {
                    return total + productInfo.product.price * productInfo.orderSales;
                }
                return total;
            }, 0);
            return parseFloat(total.toFixed(2));
        }
        return 0;
    }
  },
};
</script>

<style scoped>
.order-container {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: 100vh;
}
.register-link {
    font-size: 16px;
    color: blue;
    text-decoration: underline;
    text-align: center;
    margin-top: 20px;
    cursor: pointer;
}
/* 订单筛选 */
.order-filter {
  display: flex;
  justify-content: space-around;
  margin-bottom: 15px;
  background-color: #fff;
  padding: 10px 0;
  border-radius: 8px;
}

.filter-item {
  font-size: 14px;
  color: #666;
  padding: 5px 10px;
}

.filter-item.active {
  color: #ff6700;
  font-weight: bold;
  border-bottom: 2px solid #ff6700;
}

/* 订单列表 */
.order-list {
  margin-bottom: 60px;
}

.order-item {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

/* 店铺信息 */
.store-info {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 10px;
}

.store-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}

.store-name {
  font-size: 15px;
  font-weight: bold;
  flex: 1;
}

.order-status {
  font-size: 14px;
  color: #ff6700;
}

.order-time {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

/* 商品列表 */
.product-list {
  margin-bottom: 10px;
}

.product-item {
  display: flex;
  margin-bottom: 10px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 10px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 14px;
  color: #333;
}

.product-price {
  font-size: 15px;
  color: #ff6700;
  font-weight: bold;
}

.product-quantity {
  font-size: 13px;
  color: #999;
  align-self: flex-end;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.total-price {
  font-size: 14px;
  color: #666;
}

.order-actions {
  display: flex;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 13px;
  margin-left: 10px;
}

.confirm-btn {
  border: 1px solid #ff6700;
  color: #ff6700;
}

.cancel-btn {
  border: 1px solid #999;
  color: #666;
}
</style>